﻿<%@ Page Title="" Language="C#" MasterPageFile="~/master/Attendance.master" AutoEventWireup="true" CodeFile="My.aspx.cs" Inherits="LDAP.Web.View.Attendance.My" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <link rel="stylesheet" href="<%= StaticDomain %>/scripts/util/ui_bubble/ui_bubble.css?r=<%= R %>" />
    <link rel="stylesheet" href="<%= StaticDomain %>/scripts/util/JqModal/JqPopU.css?r=<%= R %>" />
    <style type="text/css">
        .niceTab th {
            line-height:70px;
        }
        .niceTab td {
            height:120px;
        }
        .kqDetail th,.kqDetail td, .formDetail th,.formDetail td {
            line-height:24px; height:24px; font-size:12px; color:black;
        }
        .kqDetail td, .formDetail td {
            background-color:white;
            padding: 3px 12px; 
            border-top:1px solid #E6E6E6;
        }
        .formDetail td {
            text-align: left;
        }
        .formDetail label {
            display:inline-block; margin-right:16px; line-height:24px;
        }
        .formDetail ol {
            padding-left: 20px;
            margin-bottom:0;
        }
        .formDetail li{
            list-style-position:outside;
        }
        .tipss span {
            color: red;
        }
        .tipss .tipsss {
            padding:0 5px;
            color: black;
        }
    </style>
    
    <script type="text/javascript" src="<%= StaticDomain %>/scripts/util/My97DatePicker/WdatePicker.js"></script>
    <style type="text/css">
        .Wdate {
            height:34px;
        }
    </style>
    <script type="text/javascript" src="<%= StaticDomain %>/scripts/util/ui_bubble/ui_bubble.js?r=<%= R %>"></script>
    <script type="text/javascript" src="<%= StaticDomain %>/scripts/util/JqModal/JqPopU.js?r=<%= R %>"></script>
    <script type="text/javascript" src="<%= StaticDomain %>/scripts/util/jquery-ajaxupload/jquery.ajaxupload.js"></script>
    <script type="text/javascript" src="<%= StaticDomain %>/scripts/util/template/trimpath-template.js"></script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div>
      <nav class="navbar navbar-default" role="navigation">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">选择月份</a>
        </div>
        <div class="collapse navbar-collapse">
          <form class="navbar-form navbar-left" role="search">
            <div class="form-group">
              <input type="text" class="form-control Wdate" value="<%= Year %>年<%= Month.ToString().PadLeft(2,'0') %>月" id="month" onfocus="WdatePicker({skin:'whyGreen',dateFmt:'yyyy年MM月',maxDate:'<%= DateTime.Today.Year %>-<%= DateTime.Today.Month.ToString().PadLeft(2,'0') %>-01'})" />
            </div>
            <button class="btn btn-default" type="button" id="transfer">确定</button>
          </form>
        </div>
      </nav>
    </div>

    <table class="niceTab" cellspacing="0" cellpadding="0" border="0">
        <tr>
            <% for (int i = (int)DayOfWeek.Sunday; i <= (int)DayOfWeek.Saturday; i++)
               { %>
                   <th><%= System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[i] %></th>
             <%  } %>
        </tr>
        
        <asp:Literal ID="Calender" runat="server"></asp:Literal>
    </table>

    <textarea name="demoItem" id="demoItem" style="display:none">
        <table class="niceTab formDetail" cellspacing="0" cellpadding="0" border="0">
            <tr>
                <th>日期</th>
                {if ExceptionEndDate-ExceptionStartDate!=0}                   
                    <td>@{ExceptionStartDate.Format("yyyy-MM-dd")} - @{ExceptionEndDate.Format("yyyy-MM-dd")}</td>
                {elseif}
                    <td>@{ExceptionStartDate.Format("yyyy-MM-dd")}</td><%--<th>时段</th><td>{if DurationType ==1}上午{elseif DurationType==2}下午{else}全天{/if}</td>--%>
                {/if}
                <th>时长</th><td>@{showTimeTypeName(Duration)}</td>
            </tr>
            <tr><th>类型</th><td colspan="3">@{showTypeName(Type)}</td></tr>
            <tr><th>异常证明</th><td colspan="3"><ol id="attachShow" style="line-height:24px;"></ol></td></tr>
            {if PassUserId!=null}
            <tr><th>审批人</th><td>@{getAngelName(PassUserId)}</td><th>审批时间</th><td>@{PassTime.Format("yyyy-MM-dd hh:mm")}</td></tr>
            {/if}
            <tr>
                <th>审批状态</th>
                <td colspan="3">{if Status==100}审批通过{elseif Status==10}<span style="color:red;">审批拒绝</span>{else}<span style="color:gray;">暂未审批</span>{/if}</td>
            </tr>
            {if Comment!=null && Comment!=""}
            <tr><th>批注</th><td colspan="3">@{Comment.replace(/\n/g,'<br />')}</td></tr>
            {/if}
        </table>
    </textarea>

    <script type="text/javascript">
        $(document).ready(function () {        
            $("#transfer").click(page.transfer);
            page.init();
        });

        var page = {
            uploading: false,
            handler: "/handler/attendanceControl.ashx?action=",

            transfer: function () {
                var date = $("#month").val().match(/\d+/g);
                window.location.href = "/Attendance/My.aspx?y=" + date[0] + "&m=" + date[1];
                return false;
            },

            init: function () {
                $.each($(".niceTab td[tag]"), function(){
                    $(this).attr("type", showSchedule($(this).attr("tag"), page.specialSchedule, page.schedule).type).attr("count",0);
                });

                //初始化日期数据
                $.each(page.record, function (i, q) {
                    var arr = q.date.split('/');
                    var d = new Date(new Date(arr[0], parseInt(arr[1],10) - 1, arr[2]).valueOf() + 86400000).Format("yyyy/MM/dd");
                    $(".niceTab td[tag='" + d + "']").attr("lmax", q.max.substring(0,5));
                    $(".niceTab td[tag='" + q.date + "']").attr("count", q.count).attr("min", q.min.substring(0,5)).attr("max",q.max.substring(0,5));
                });
                
                $.each(page.exceptionFormPassList, function(i,q){
                    q.CreateTime = q.CreateTime.ToDate();
                    q.ExceptionEndDate = q.ExceptionEndDate.ToDate();
                    q.ExceptionStartDate = q.ExceptionStartDate.ToDate();
                    q.PassTime = q.PassTime.ToDate();
                });

                $.each($(".niceTab td[tag]:not([class*='weekend'])"), function(){
                    var lmax = $(this).attr("lmax");
                    var exception = true;
                    if ($(this).attr("count") <= 1) { //<=1次打卡
                        if (lmax != undefined && (lmax.split(':')[0] == 4 || lmax.split(':')[0] == 5)) {
                            exception = false;
                        }
                    }
                    else {
                        exception = page.showStatus($(this)).errorCode > 0;
                    }

                    var date = new Date($(this).attr("tag"));
                    $.each(page.exceptionFormPassList, function(i,q){
                        if((q.ExceptionEndDate - date >=0) && (date - q.ExceptionStartDate>=0)){
                            //if(q.DurationType==0){ //todo: 区分上午/下午/全天
                                exception = false;
                                return false;
                            //}
                        }
                    });

                    if (exception && !$(this).hasClass("future"))
                        $(this).addClass("exception");
                });

                $.each(page.exceptionForm, function(i,q){
                    q.CreateTime = q.CreateTime.ToDate();
                    q.ExceptionEndDate = q.ExceptionEndDate.ToDate();
                    q.ExceptionStartDate = q.ExceptionStartDate.ToDate();
                    q.PassTime = q.PassTime.ToDate();
                });

                $(".niceTab td[tag]").click(function (event) { page.showTip(event, this); });
            },

            showStatus: function (obj, flag) {
                var errorCode = 0;
                var type = $(obj).attr("type");
                var noRecord = "无打卡记录";
                var attendanceType = 0;
                var object = $("<tr><td class='tipss'><span class='tipsss'></span><span></span></td><td class='tipss'><span class='tipsss'></span><span></span></td></tr>");
                
                var lmax = null;
                if($(obj).attr("lmax") != undefined){
                    lmax = $(obj).attr("lmax").split(':')[0];
                }

                var tempCount = $(obj).attr("count");
                if (tempCount == 0) {
                    errorCode = 1; //一整天没打卡
                    var forget = true;
                    if (lmax != null) {
                        var lMaxTime = lmax.split(':');
                        if (lMaxTime[0] == 4 || lMaxTime[0] == 5) {
                            forget = false;
                            $(object).find("td:eq(0) span:eq(0)").html("正常（需核实前一天延时）");
                            $(object).find("td:eq(1) span:eq(0)").html("正常（需核实前一天延时）");
                        }
                    }
                    if (forget) {
                        $(object).find("td:eq(0) span:eq(0)").html(noRecord);
                        $(object).find("td:eq(1) span:eq(0)").html(noRecord);
                    }
                }
                else if(tempCount == 1){
                    errorCode = 2; //指打卡一次
                    var str ="";

                    var timeArray = $(obj).attr("min").split(':');
                    if(timeArray[0]>5 && timeArray[0]<12){
                        $(object).find("td:eq(0) span:eq(0)").html($(obj).attr("min"));
                        $(object).find("td:eq(1) span:eq(0)").html(noRecord);
                        str = showAttendanceStatus($(obj).attr("min"), 1, type, lmax, $(obj).hasClass("weekend"));
                        $(object).find("td:eq(0) span:eq(1)").html(str);
                        if(str!="" && str!="休日出勤"){
                            errorCode = 3;
                        }
                        else if(str=="休日出勤"){
                            errorCode = -1;
                        }
                    }
                    else{
                        $(object).find("td:eq(1) span:eq(0)").html($(obj).attr("max"));
                        $(object).find("td:eq(0) span:eq(0)").html(noRecord);
                        str = showAttendanceStatus($(obj).attr("max"), 2, type, lmax, $(obj).hasClass("weekend"), $(obj).attr("min"));
                        $(object).find("td:eq(1) span:eq(1)").html(str);
                        if(str!="" && str!="休日出勤" && str!="延时"){
                            errorCode = 3;
                        }
                        else if(str=="休日出勤"){
                            errorCode = -1;
                        }
                    }
                }
                else {
                    var str ="";
                    $(object).find("td:eq(0) span:eq(0)").html($(obj).attr("min"));
                    str = showAttendanceStatus($(obj).attr("min"), 1, type, lmax, $(obj).hasClass("weekend"));
                    $(object).find("td:eq(0) span:eq(1)").html(str);
                    if(str!="" && str!="休日出勤"){
                        errorCode = 3;
                    }
                    else if(str=="休日出勤"){
                        errorCode = -1;
                    }
                    
                    $(object).find("td:eq(1) span:eq(0)").html($(obj).attr("max"));
                    str = showAttendanceStatus($(obj).attr("max"), 2, type, lmax, $(obj).hasClass("weekend"), $(obj).attr("min"));
                    $(object).find("td:eq(1) span:eq(1)").html(str);
                    if(str!="" && str!="休日出勤" && str!="延时"){
                        errorCode = 3;
                    }
                    else if(str=="休日出勤"){
                        errorCode = -1;
                    }
                }
                return { errorCode: errorCode, str: $(object).html() };
            },

            showForms: function(date){
                var arr = date.split('/');
                var date = new Date(arr[0], parseInt(arr[1],10) - 1, arr[2]);
                
                var list = [];
                $.each(page.exceptionForm, function(i,q){
                    if(q.ExceptionStartDate<=date && date<= q.ExceptionEndDate)
                        list.push(q);
                });

                if(list.length==0)
                    return "";

                var html = [];
                html.push('<p style="margin:5px 0;font-weight:bold;">相关单据</p>');
                html.push('<div class="formDetail" id="formlist"><ol>');
                $.each(list, function(i,q){
                    html.push('<li><a href="javascript:void(0)" id="ef_ex_'+q.Id+'" onclick="page.showExceptionForm('+ q.Id + ')">' +(q.Type<=11&&q.Type>=9?"加班单":"异常单") +"[" + showTypeName(q.Type)+'] (单据号: '+q.Id+')</a> '+(q.PassUserId==null?"未审批": (q.Status==100?"审批通过" :"审批拒绝"))+'</li>');
                });
                html.push('</ol></div>');
                return html.join('');
            },

            showExceptionForm: function(id){
                var match = null;
                $.each(page.exceptionForm, function(i,q){
                    if(q.Id==id){
                        match = q;
                        return false;
                    }
                });

                if(match==null){
                    alert("一定是哪里出什么问题了，刷新页面看看");
                    window.location.reload();
                    return false;
                }

                page.popU = page.popU || new PopU();
                page.popU.initPop({
                    type: 'string',
                    title: "异常单据",
                    contents: TrimPath.processDOMTemplate("demoItem", match),
                    w: 650,
                    onYesFn: match.Status ==0 ? function () {
                        if(confirm("您确定删除当前单据么？")){
                            $.post(page.handler +"delExceptionForm", {id: id}, function(data){
                                if(data && data.code==1){
                                    var temp = [];
                                    $.each(page.exceptionForm, function(i,q){
                                        if(q.Id!=id)
                                            temp.push(q);
                                    });
                                    page.exceptionForm = temp;
                                    $("#ef_ex_"+id).parent().remove();
                                    if(page.popU)
                                        page.popU.close();
                                }
                                else{
                                    alert("出错了，刷新看看？");
                                    window.location.reload();
                                }
                            },"json");
                        }
                    } : undefined,
                    ShowYesBtnValue: "删除",
                    onNoFn: function(){},
                    ShowNoBtnValue: "关闭"     
                });
                page.popU.showPop();

                $.get(page.handler +"getAttachementInfo", {id: match.Attachement}, function(data){
                    if(data && data.code==1){
                        $.each(data.list, function(i,q){
                            $("#attachShow").append("<li><a target='_blank' href='" + q.Path + "'>" + q.FileName + "</a></li>");                                
                        });
                    }
                    else{
                        $("#attachShow").parent().html("加载附件异常，请刷新后重试");
                    }
                },"json");
            },

            showTip: function (event, obj) {
                var p = page.getMousePosition(event);
                var html = [];
                html.push("日期：" + $(obj).attr("tag") + ($(obj).hasClass("weekend") ? " [休息日]" : ""));

                if ($(obj).attr("count")>0 || !$(obj).hasClass("weekend")) {
                    var schedule = showSchedule($(obj).attr("tag"), page.specialSchedule, page.schedule);
                    html.push("<p style='padding-top:8px;'>当天班次：" + schedule.name + "</p>");

                    if(new Date() - new Date($(obj).attr("tag"))>=0){
                        html.push('<table class="niceTab kqDetail" cellspacing="0" cellpadding="0" border="0">');
                        html.push('<tr><th>上班</th><th>下班</th></tr>');
                        var status = page.showStatus(obj, true);
                        html.push(status.str);
                        html.push('</table>');

                        if(status.errorCode!=0)
                            html.push("<br /><p>");
                        if(status.errorCode>0)
                            html.push("<input type='button' class='btn btn-default btn-sm btn-info' id='btnException' value='填写单据'/>");
                        if(status.errorCode==-1)
                            html.push("<input type='button' class='btn btn-default btn-sm btn-info' id='btnMore' value='填写加班单'/>");
                        if(status.errorCode!=0)
                            html.push("</p>");
                    }
                    else{
                        html.push("<p style='color:gray'>时间还没到呢，你猜到时候的考勤会是怎样的？</p>");
                        html.push("<input type='button' class='btn btn-default btn-sm btn-info' id='btnException' value='提前填写单据'/>");
                    }
                    html.push(page.showForms($(obj).attr("tag")));
                }
                else if($(obj).hasClass("weekend")){
                    html.push("<br /><br /><input type='button' class='btn btn-default btn-sm btn-info' id='btnMore' value='填写加班单'/>");
                    html.push(page.showForms($(obj).attr("tag")));
                }

                new ui_bubble({
                    content: html.join(''),
                    pointX: p.x,
                    pointY: p.y
                });

                if($("#btnException").length>0) $("#btnException").click(function(){page.initExceptionForm($(obj).attr("tag"),0)});
                if($("#btnMore").length>0) $("#btnMore").click(function(){ page.initExceptionForm($(obj).attr("tag"), 1);});
            },

            initExceptionForm: function(date, type){
                var con = [];
                Array.prototype.push.call(con,
                    '<table class="niceTab formDetail" cellspacing="0" cellpadding="0" border="0">'
                    , '<tr><th>日期</th><td><label><input type="radio" value="0" checked="checked" name="durationType" />' + date + '</label>'
                    , '<br /><label><input type="radio" value="1" name="durationType" />' + date + ' - <input type="text" class="form-control Wdate" style="width:150px; display: inline-block;" id="exEndDay" onfocus="WdatePicker({skin:\'whyGreen\',minDate:\''+ date+'\'})" />'
                    , '</label></td></tr>'
                    //, '<tr><th>时段</th><td><label><input type="radio" name="ning" checked="checked" value="1"/>上午</label><label><input type="radio" name="ning" value="2" />下午</label><label><input value="0" type="radio" name="ning" />全天</label></td></tr>'
                    , '<tr><th>时长</th><td><input type="text" id="duration" style="width:50px; display: inline-block;" class="form-control" /> <select id="dayType"><option value="1">天</option><option value="2">小时</option></select><span style="padding-left:15px; color:gray;">请假类型（含调休）的请填写影响天数，考勤异常(加班延迟，异常）的不需要</span></td></tr>'
                    , '<tr><th>类型</th><td id="detail_tag">'
                    , '</td></tr>'
                    , '<tr><th>证明材料</th><td style="padding-top:12px;"><input type="button" id="upload" class="btn btn-default btn-info" value="上传附件" /><ol id="attachShow" style=" line-height:24px;"></ol></td></tr>'
                    , '</table><br />');
                
                page.popU = page.popU || new PopU();
                page.popU.initPop({
                    type: 'string',
                    title: (type==0?"异常":"加班") + "单据填写",
                    contents: con.join(''),
                    w: 650,
                    onYesFn: function () { page.submitForm(date); },
                    onNoFn: function () { },
                    tip: "<span style='color:red'>如果附件为邮件文件，请举手之劳再多上传一份邮件截图。</span>"
                });
                page.popU.showPop();
                
                con = [];
                if(type==0){
                    Array.prototype.push.call(con
                        , '<label><input type="radio" name="type" value="0" />加班延时</label>'
                        , '<label><input type="radio" name="type" value="1" />异常</label>'
                        , '<label><input type="radio" name="type" value="2" />事假</label>'
                        , '<label><input type="radio" name="type" value="3" />病假</label>'
                        , '<label><input type="radio" name="type" value="4" />丧假</label>'
                        , '<label><input type="radio" name="type" value="5" />产假</label><br />'
                        , '<label><input type="radio" name="type" value="6" />法定年假</label>'
                        , '<label><input type="radio" name="type" value="7" />福利年假</label>'
                        , '<label><input type="radio" name="type" value="8" />调休</label>'
                        , '<label><input type="radio" name="type" value="12" />其他</label>');
                }
                else{
                    Array.prototype.push.call(con
                        , '<label><input type="radio" name="type" value="9" />调休加班</label>'
                        , '<label><input type="radio" name="type" value="10" />周末值班</label>'
                        , '<label><input type="radio" name="type" value="11" />公假值班</label>');

                    $("#duration").parent().find("span").hide();
                }

                $("#detail_tag").html(con.join(''));
                
                page.ajaxUploadObj = new AjaxUpload('upload', {
                    action: "/handler/upload.ashx?action=uploadFile",
                    autoSubmit: true,
                    data: { targetType: 1 },
                    onSubmit: function (file, ext) {
                        $("#upload").removeClass("btn-info").val("上传中..");
                        page.uploading = true;
                        this.disable();
                    },
                    onChange: function (file, ext) {
                        //this.enable();
                    },
                    responseType: 'json',
                    onComplete: function (file, response) {
                        page.uploading = false;
                        if(response.code==1){
                            $("#upload").addClass("btn-info").val("上传附件");
                            if (response.error) {
                                alert(response.error);
                            }
                            else {
                                $("#attachShow").append("<li><a id='attc_" + response.id + "' target='_blank' href='" + response.url + "'>" + file + "</a><button type='button' class='btn btn-link' onclick='$(this).parent().remove();'>删除</button></li>");
                            }
                            $("#btnAdd").unbind("click").click(page.submit);
                        }
                        else{
                            alert(response.msg);
                        }
                        this.enable();
                    }
                });
            },

            submitForm: function (date) {
                if (page.uploading) {
                    alert("附件上传中，缓缓再试");
                    return false;
                }

                //var duration1 = $("input[name='ning']:checked").val();
                var duration = $("#duration").val();
                var durationType = $("input[name='durationType']:checked").val();
                var type = $("input[name='type']:checked").val();
                //var list =
                
                var endTime = $("#exEndDay").val();
                if(durationType == 1 && endTime==""){
                    alert("日期为时段类型，请选择结束时间");
                    $("#exEndDay").focus();
                    return false;
                }
                if(durationType==0){
                    endTime="";
                }
                
                if (type == undefined) {
                    alert("请先选择类型");
                    return false;
                }
                if(type<=8 && type>=2 && duration==""){
                    alert("请假类型（含调休）的请填写影响天数/小时");
                    return false;
                }

                var ids = [];
                if ($("#attachShow li a").length == 0) {
                    alert("请至少上传一个附件作为依据证明");
                    $("#duration").focus();
                    return false;
                }

                $.each($("#attachShow li a"), function (i, q) {
                    ids.push($(q).attr("id").replace(/attc_/g, ''));
                });
                var dt = $("#dayType").val();
                if(dt == 1)
                    duration= duration * 8;
                $.post(page.handler+ "submitExceptionForm", { startTime: date.replace(/\//g,'-'), endTime: endTime, duration: duration, type: type, ids: ids.join(',') }, function (data) {
                    if(data){
                        if(data.code==1){
                            data.ef.CreateTime = data.ef.CreateTime.ToDate();
                            data.ef.ExceptionEndDate = data.ef.ExceptionEndDate.ToDate();
                            data.ef.ExceptionStartDate = data.ef.ExceptionStartDate.ToDate();
                            data.ef.PassTime = data.ef.PassTime.ToDate();
                            page.exceptionForm.push(data.ef);
                            $("#formlist ol").append('<li><a href="javascript:void(0)" onclick="page.showExceptionForm('+ data.ef.Id + ')">异常单['+ showTypeName(data.ef.Type)+'] (单据号: '+data.ef.Id+')</a> 未审批</li>');                                
                            
                            page.timeOuter=window.setTimeout(function(){
                                $(".ft .tip").html("提交成功，1秒后自动关闭。&nbsp;")
                                page.timeOuter=window.setTimeout(function(){
                                    if(page.popU)
                                        page.popU.close();
                                },1000);
                            },1000);
                            $(".ft .tip").html("提交成功，2秒后自动关闭。&nbsp;").css({color:"red"});
                        }
                        else{
                            alert(data.msg);
                        }                        
                    }else{
                        alert("啊哦，好像有点问题，刷新页面或者缓缓再试？");
                    }
                }, "json");
            },

            getMousePosition: function (ev) {
                ev = ev || window.event;
                if (ev.pageX || ev.pageY)
                    return { x: ev.pageX, y: ev.pageY };
                else
                    return {
                        x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                        y: ev.clientY + document.body.scrollTop - document.body.clientTop
                    };
            }
        };

        page.record = <%= AccessRecord %>;
        page.schedule = <%= ToJson(Schedule) %>;
        page.specialSchedule = <%= ToJson(SpecialSchedule) %>;
        page.exceptionForm = <%= ToJson(ExceptionForm) %>;
        page.exceptionFormPassList = <%= ToJson(ExceptionFormPassList) %>;
        page.angelList = <%= ToJson(AngelList) %>;
    </script>
</asp:Content>